from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from app.models import factor as models

from app.common.exceptions import GenericException
from app.common.enums.resp_enum import ErrTypes

import logging
logger = logging.getLogger(__name__)

def get_factors(db: Session, skip: int = 0, limit: int = 10):
    return db.query(models.Factor).order_by(models.Factor.create_time.desc()).offset(skip).limit(limit).all()

def get_factor(db: Session, factor_no: str):
    return db.query(models.Factor).filter(models.Factor.factor_no == factor_no).first()

def get_factor_fee(db: Session, factor_no: str, product_code: str, fee_mode: int):
    try:
        factor_fee = db.query(models.FactorFee).filter(
            models.FactorFee.factor_no == factor_no,
            models.FactorFee.product_code == product_code,
            models.FactorFee.fee_mode == fee_mode
            ).first()
        return factor_fee
    except Exception as err:
        logger.exception(err)
        raise GenericException(ErrTypes.db_query_error)

def get_factor_by_id(db: Session, factor_id: int):
    return db.query(models.Factor).filter(models.Factor.fid == factor_id).first()


